﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using K2.Listener.Entity;
using K2.Sync.Entity;
using MongoDB.Driver;

namespace K2.Sync.Service.Handlers
{
    public class ActInstSlotHandler
    {
        private static IMongoDatabase db = MongoFactory.GetDatabase();
        public void HandleWorklistMsg(ActInstSlotListenerEntity msg)
        {
            Console.WriteLine("Insert trigger!");
            var processedList = new List<ProcessedEntity>();
            processedList.Add(new ProcessedEntity { ActInstID = msg.ActInstID });
            var data = new ActInstSlotMongoEntity
            {
                ProcInstID = msg.ProcInstID,
                User = msg.User,
                ProcessedList = processedList
            };
            var record = db.GetCollection<ActInstSlotMongoEntity>("processed")
                .Find(x => x.ProcInstID == msg.ProcInstID && x.User == msg.User).FirstOrDefault();
            if (record == null)
            {
                db.GetCollection<ActInstSlotMongoEntity>("processed").InsertOne(data);
            }
            else
            {
                record.ProcessedList.Add(new ProcessedEntity { ActInstID = msg.ActInstID });
                db.GetCollection<ActInstSlotMongoEntity>("processed")
                    .FindOneAndUpdate(x => x.ProcInstID == msg.ProcInstID && x.User == msg.User,
                    Builders<ActInstSlotMongoEntity>.Update.Set(x => x.ProcessedList, record.ProcessedList));
            }
        }
    }
}
